"""
@author: huangll
@email: ll.huang@hzgosun.com
@time: 2019/6/5 9:32

人口管理的增改删查自动化测试用例编写
"""

import os
import unittest
from time import sleep

from selenium.webdriver.common.keys import Keys

from common.functions import save_screenshot, get_data_file_abs_path
from common.decorators import mkdir_classname, log4gs
from common.settings import TAG, DATA_DIR
from common.vue.select import DropDownSelect, OperateSelect
from pages.personListPage import PersonListPage


@log4gs
@mkdir_classname(TAG)
class PersonListTest(unittest.TestCase):
    """人口库管理功能测试"""
    @classmethod
    def setUpClass(cls):
        cls.log.info('=' * 30 + "开始人口库管理功能测试({})".format(__class__.__name__) + '=' * 30)
        cls.page = PersonListPage('/DataManage/PersonList')

    @classmethod
    def tearDownClass(cls):
        cls.log.info('=' * 30 + "结束人口库管理功能测试({})".format(__class__.__name__) + '=' * 30)
        cls.page.driver.quit()

    def setUp(self):
        self.log.info('>>>>>开始执行用例：{} {}'.format(self.id(), self.shortDescription()))
        sleep(1)

    def tearDown(self):
        self.log.info('<<<<<结束执行用例：{} {}'.format(self.id(), self.shortDescription()))

    #@unittest.skip
    def test_1_page(self):
        """翻页测试"""
        sleep(1)
        self.log.debug("首页共有：{}页数据".format(self.page.turnPage.total_page))
        self.log.debug("当前处于第：{}页数据".format(self.page.turnPage.current_page))
        self.log.debug("共有：{}条数据".format(self.page.turnPage.total_num))
        sleep(2)
        self.assertNotEqual(self.page.turnPage.total_page, 1, msg="页数过少，无法进行翻页测试")
        try:
            self.page.turnPage.next_page.click()
            self.assertEqual(self.page.turnPage.current_page, '2')
            sleep(2)
            try:
                self.page.turnPage.next_page.click()
                self.assertEqual(self.page.turnPage.current_page, '3')
                sleep(2)
                self.page.turnPage.prev_page.click()
                self.assertEqual(self.page.turnPage.current_page, '2')
                sleep(2)
                self.page.turnPage.input.clear()
                self.page.turnPage.input.send_keys(3)
                self.page.turnPage.input.send_keys(Keys.ENTER)
                self.assertEqual(self.page.turnPage.current_page, '3')
            except Exception as e:
                print("无法执行翻页测试" % e)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("翻页功能测试失败")

    #@unittest.skip
    def test_2_add_person(self):
        """添加人员"""
        try:
            self.page.table.add_btn.click()
            sleep(1)
            self.page.addPerson.name.send_keys("测试自动化1")
            DropDownSelect(self.page.addPerson.gender, "男")
            self.page.addPerson.id_.send_keys("440304198506020254")
            self.page.addPerson.region.click()
            self.page.addPerson.region_selector.select("广东省-深圳市-福田区")
            self.page.addPerson.region.click()  # 收起区域选择器
            sleep(1)
            self.page.addPerson.grid.click()
            self.page.addPerson.grid_selector.select("江西省-深圳市网格-深圳市福田区网格")
            self.page.addPerson.grid.click()   # 收起网格选择器
            sleep(1)
            self.page.addPerson.flag_person_tag.click()  # 切换到人物信息编辑页
            self.page.addPerson.person_imei.send_keys('123456')
            self.page.addPerson.guardian_name.send_keys('彭大')
            self.page.addPerson.guardian_phont.send_keys('18112341234')
            self.page.addPerson.village_cadre_name.send_keys('彭干部')
            self.page.addPerson.village_cadre_phone.send_keys('18112341235')
            self.page.addPerson.confirm.click()
            # 检查是否加成功
            sleep(1)
            DropDownSelect(self.page.searchTools.keyword_dropdown_list, "姓名")  # 关键字选择姓名
            self.page.searchTools.keyword_input.send_keys("测试自动化1")  # 关键字输入测试自动化1
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("测试自动化1")
            self.assertTrue(result, "通过姓名:测试自动化1查询到了测洁自动化1")
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            sleep(1)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot(self,"添加人员失败")

    #@unittest.skip
    def test_3_alter_person(self):
        """修改人员"""
        try:
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            DropDownSelect(self.page.searchTools.keyword_dropdown_list, "姓名")  # 关键字选择姓名
            self.page.searchTools.keyword_input.send_keys("测试自动化1")  # 关键字输入测试自动化1
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("测试自动化1")

            OperateSelect(result, "编辑")
            sleep(1)
            self.page.modifyPerson.name.clear()
            self.page.modifyPerson.name.send_keys("百花缭乱")  # 用户名修改为百花缭乱
            DropDownSelect(self.page.modifyPerson.gender, "女")  # 性别修改为女
            self.page.modifyPerson.date.clear()
            sleep(3)
            self.page.modifyPerson.date.send_keys('1993-12-17')
            sleep(3)
            self.page.modifyPerson.confirm.click()

            sleep(1)
            self.page.searchTools.reset_btn.click()
            DropDownSelect(self.page.searchTools.keyword_dropdown_list, "姓名")  # 关键字选择姓名
            self.page.searchTools.keyword_input.send_keys("百花缭乱")  # 关键字输入百花缭乱
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("百花缭乱")
            self.assertTrue(result, "通过姓名:百花缭乱查询到了百花缭乱")
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            sleep(1)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("修改人员失败")

    #@unittest.skip
    def test_4_delete_person(self):
        """删除人员"""
        try:
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            DropDownSelect(self.page.searchTools.keyword_dropdown_list, "姓名")  # 关键字选择姓名
            self.page.searchTools.keyword_input.send_keys("百花缭乱")  # 关键字输入百花缭乱
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("百花缭乱")

            OperateSelect(result, "删除") #点击删除入口

            sleep(1)
            self.page.deletePerson.confirm.click()  #确定删除
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("删除人员失败")

    #@unittest.skip
    def test_5_search(self):
        """
        利用subTest进行姓名、身份证、IMSI、手机号码查询
        """
        search_list = [
            {
                'condition': "姓名",
                'input': "于叶澜",
                'expectation': "于叶澜"
            },
            {
                'condition': "身份证",
                'input': "440304198506020034",
                'expectation': "沈冬儿"

            },
            {
                'condition': "IMSI",
                'input': "460017145625002",
                'expectation':"易雪萍"
            },
            {
                'condition': "手机号码",
                'input': "18111110050",
                'expectation': "尹靖儿"
            },
        ]
        try:
            self.page.searchTools.reset_btn.click()  #点击重置按钮
            for item in search_list:
                condition = item.get('condition')
                input_ = item.get('input')
                expectation = item.get('expectation')
                # 利用subTest对这种只是输入数据不一样，步骤一样的用例，进行统一测试
                with self.subTest(**item):
                    self.log.info("用以下数据进行搜索测试：\n{}".format(item))
                    DropDownSelect(self.page.searchTools.keyword_dropdown_list, condition)   # 关键字选择姓名
                    self.page.searchTools.keyword_input.send_keys(input_)   # 关键字输入于叶澜
                    self.page.searchTools.search_btn.click()   # 点击检索按钮
                    sleep(1)
                    try:
                        result = self.page.table.get_row(expectation)
                        self.assertTrue(result, msg="没有找到结果：{}".format(expectation))
                        self.log.info("用例'{}'执行成功".format(self.id()))
                    except Exception:
                        self.log.error("用例'{}'执行失败,".format(self.id()), exc_info=True)
                    self.page.searchTools.reset_btn.click()  # 点击重置按钮
                    sleep(1)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("查询测试失败")

    @unittest.skip
    def test_6_search(self):
        """标签查询"""
        try:
            DropDownSelect(self.page.searchTools.keyword_dropdown_list, "标签")
            DropDownSelect(self.page.searchTools.tag_dropdown_list, "矫正人员")
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("田永康")
            self.assertTrue(result, "通过标签:矫正人员查询到了田永康")
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            sleep(1)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("标签查询失败")

    @unittest.skip
    def test_7_search(self):
        """区域、小区查询"""
        try:
            DropDownSelect(self.page.searchTools.region_dropdown_list, "区域")
            self.page.searchTools.region_region_input.click()
            sleep(1)
            self.page.searchTools.region_region_selector.select("广东省-深圳市-福田区")
            DropDownSelect(self.page.searchTools.community_dropdown_list, "蓝色海云居")
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("丁元嘉")
            self.assertTrue(result, "通过区域:广东省-深圳市-福田区，小区：蓝色海云居查询到了丁原嘉")
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            sleep(1)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("区域小区查询失败")

    @unittest.skip
    def test_8_search(self):
        """网格查询"""
        try:
            DropDownSelect(self.page.searchTools.region_dropdown_list, "网格")
            self.page.searchTools.region_grid_input.click()
            sleep(1)
            self.page.searchTools.region_grid_selector.select("江西省-深圳市网格")
            sleep(2)
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("郝代曼")
            self.assertTrue(result, "通过网格:江西省-深圳网格查询到了郝代曼")
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            sleep(1)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("网格查询失败")

    #@unittest.skip
    def test_10_files(self):
        """导入人员"""
        try:
            self.page.table.add_files_btn.click()
            sleep(1)
            self.page.filesPerson.daoru.send_keys(get_data_file_abs_path("people_excel.xlsx"))
            sleep(6)
            self.page.filesPerson.confirm.click()
            # 检查是否加成功
            sleep(5)
            DropDownSelect(self.page.searchTools.keyword_dropdown_list, "姓名")  # 关键字选择姓名
            self.page.searchTools.keyword_input.send_keys("宋尔云")
            self.page.searchTools.search_btn.click()  # 点击检索按钮
            sleep(1)
            result = self.page.table.get_row("宋尔云")
            self.assertTrue(result, "通过姓名:宋尔云查询到了宋尔云")
            self.page.searchTools.reset_btn.click()  # 点击重置按钮
            sleep(1)
        except Exception as e:
            print("导入用户执行失败:%r" % e)
            save_screenshot("导入人员失败")

    @unittest.skip
    def test_9_clear(self):
        """清除网格、小区、区域"""
        try:
            # 清空已选的网格（ElementType.GRID）
            DropDownSelect(self.page.searchTools.region_dropdown_list, "网格")
            self.page.searchTools.region_grid_input.click()
            self.page.searchTools.region_grid_selector.select("江西省-太原市网格")
            self.page.searchTools.region_grid_input.clear()
            # 清空已选的小区（ElementType.DROPDOWN_LIST）、区域（ElementType.REGION）
            DropDownSelect(self.page.searchTools.region_dropdown_list, "区域")
            self.page.searchTools.region_region_input.click()
            self.page.searchTools.region_region_selector.select("山西省-太原市-小店区")
            DropDownSelect(self.page.searchTools.community_dropdown_list, "太原兴达小区")
            self.page.searchTools.community_dropdown_list.clear()
            sleep(1)
            self.page.searchTools.region_region_input.clear()
            sleep(1)
        except Exception as e:
            print("用例执行失败:%r" % e)
            save_screenshot("清除网格失败")

    @unittest.skip
    def test_upload(self):
        """上传文件和VueElement举例，并删除已选的图片"""
        try:
            self.page.table.add_btn.click()
            self.page.addPerson.face_pic.send_keys(os.path.join(DATA_DIR, "测试人脸1.jpg"))
            self.page.addPerson.face_pic.clear()
            sleep(1)
            self.page.addPerson.face_pic.send_keys(os.path.join(DATA_DIR, "测试人脸2.jpg"))
        except Exception as e:
            print("用例执行失败:%r" % e)


if __name__ == '__main__':
    unittest.main()
